from django.shortcuts import render, redirect
from app01 import models

# Create your views here.


def depart_list(request):

    queryset = models.Deparment.objects.all()

    return render(request, "depart_list.html", {"queryset": queryset})


def depart_add(request):
    if request.method == "GET":
        return render(request, "depart_add.html")

    # 获取POAST提交数据
    title = request.POST.get("title")
    # 保存到数据库
    models.Deparment.objects.create(title=title)
    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):

    # 获取ID
    nid = request.GET.get('nid')
    # 删除
    models.Deparment.objects.filter(id=nid).delete()
    # 重定向到部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    if request.method == "GET":
        # 根据nid获取数据
        row_object = models.Deparment.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    title = request.POST.get("title")
    models.Deparment.objects.filter(id=nid).update(title=title)
    # 重定向到部门列表
    return redirect("/depart/list/")


def user_list(request):

    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    # 元组
    # print(obj.gender)
    # print(obj.get_gender_display())

    # 外键
    # print(obj.depart_id)
    # obj.depart  # 回根据id自动去关联的表中获取哪一行的数据



    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Deparment.objects.all()
        }
        return render(request, 'user_add.html', context)

    # 获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')

    # 添加到数据库中
    models.UserInfo.objects.create(
        name=user,
        password=pwd,
        age=age,
        account=account,
        create_time=ctime,
        gender=gender,
        depart_id=depart_id
    )
    return redirect("/user/list/")


############################    modelForm示例   ############################
from django import forms


class UserModelForm(forms.ModelForm):

    # 定义Meta内部类，用于配置ModelForm的元数据
    class Meta:
        # 指定该表单对应的模型是models模块中的UserInfo类
        # 表单的字段将基于该模型的字段自动生成
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环所有插件 添加class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """添加用户model版"""
    if request.method == "GET":
        form = UserModelForm()
        return render(request, "user_model_form_add.html", {"form": form})

    # 用户使用POST提交数据,需要数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 校验成功
        # 将数据保存到数据库
        form.save()
        return redirect('/user/list/')
    else:
        # 校验失败，在页面上显示错误信息
        return render(request, "user_model_form_add.html", {"form": form})


def user_edit(request, nid):
    """编辑用户"""

    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        # 根据id去数据库获取要编辑的那一行数据

        form = UserModelForm(instance=row_object)
        return render(request, "user_edit.html", {"form": form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request, "user_edit.html", {"form": form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")


def pretty_list(request):
    """靓号列表"""

    # select * from 表 order by level desc
    queryset = models.PrettyNum.objects.all().order_by("-level")

    return render(request, "pretty_list.html", {'queryset': queryset})


from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class PrettyModelForm(forms.ModelForm):
    mobile = forms.CharField(
        # 验证方式1:字段+正则
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]    # 添加正则表达式要求
    )

    class Meta:
        model = models.PrettyNum
        # fields = ['mobile', 'price', 'level', 'status'] 自定义字段
        # fields = "__all__" 所有字段
        # exclude = ['level'] 排除哪个字段

        fields = ['mobile', 'price', 'level', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环所有插件 添加class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证方式2:钩子
    # def clean_mobile(self):
    #     # 获取用户输入的值中的mobile
    #     txt_mobile = self.cleaned_data["mobile"]
    #     if len(txt_mobile) != 11:
    #         # 验证不通过
    #         raise ValidationError("格式错误")
    #     # 验证通过,返回用户输入的值
    #     return txt_mobile


    def clean_mobile(self):
        # 获取用户输入的值中的mobile
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()

        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在")
        # 验证通过,返回用户输入的值
        return txt_mobile


def pretty_add(request):
    """添加靓号"""
    if request.method == "GET":
        form = PrettyModelForm()

        return render(request, "pretty_add.html", {"form": form})

    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, "pretty_add.html", {"form": form})


class PrettyEditModelForm(forms.ModelForm):
    # mobile = forms.CharField(disabled=True, label="手机号")
    mobile = forms.CharField(
        # 验证方式1:字段+正则
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]  # 添加正则表达式要求
    )
    class Meta:
        model = models.PrettyNum
        # fields = ['mobile', 'price', 'level', 'status'] 自定义字段
        # fields = "__all__" 所有字段
        # exclude = ['level'] 排除哪个字段

        fields = ['mobile', 'price', 'level', 'status']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环所有插件 添加class="form-control"
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    def clean_mobile(self):
        # 获取用户输入的值中的mobile
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()

        if exists:
            # 验证不通过
            raise ValidationError("手机号已存在")
        # 验证通过,返回用户输入的值
        return txt_mobile


def pretty_edit(request, nid):
    """编辑靓号"""
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, "pretty_edit.html", {"form": form})

    form = PrettyEditModelForm(instance=row_object, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")
    return render(request, "pretty_edit.html", {"form": form})


def pretty_delete(request, nid):
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/pretty/list/")
